package com.feng.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.feng.common.utils.HttpUtils;
import com.feng.common.utils.R;
import com.feng.common.vo.MemberEntity;
import com.feng.gulimall.auth.feign.MemberFeignService;
import com.feng.gulimall.auth.vo.GiteeUser;
import com.feng.gulimall.auth.vo.SocialUser;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Controller
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;
    @GetMapping("/oauth/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        //根据code换取accessToken
        Map<String,String> map=new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","a4fbd93f05ad5807c71dd78badc75209c6713298e77561912d8144c495f27dbe");
        map.put("redirect_uri","http://auth.gulimall.com/oauth/gitee/success");
        map.put("client_secret","484ccdb66bf51c69237ffbec80091ec1df636639ae94237c03ba8a9d5d170e44");

        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<String, String>(), map, new HashMap<String, String>());
        if (response.getStatusLine().getStatusCode() == 200) {
           //获取到了accesstoken
            String json = EntityUtils.toString(response.getEntity());
            //socialUserTo没有id这个返回值
            SocialUser socialUserVo = JSON.parseObject(json, new TypeReference<SocialUser>() {});
            //知道当前是哪个社交用户
            //当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成会员账号，以后这个社交账号就对应指定的会员）
            //登录或者注册社交用户
            if (socialUserVo != null && (!StringUtils.isEmpty(socialUserVo.getAccess_token()))) {{
                Map<String, String> queryAccessToken = new HashMap<>();
                queryAccessToken.put("access_token", socialUserVo.getAccess_token());
                Map<String, String> queryHeader = new HashMap<>();
                queryHeader.put("Content-Type", "application/json;charset=UTF-8");
                HttpResponse response1 = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", queryHeader, queryAccessToken);
                if (response1.getStatusLine().getStatusCode() == 200) {
                    String json1 = EntityUtils.toString(response1.getEntity());
                    GiteeUser giteeUser = JSON.parseObject(json1, new TypeReference<GiteeUser>() {
                    });

//                    ================远程调用登录==================
                    R oauthlogin = memberFeignService.oauthlogin(giteeUser);
                    MemberEntity data = oauthlogin.getData("data",new TypeReference<MemberEntity>(){});
                    session.setAttribute("loginUser",data);
                    System.out.println(giteeUser.toString());

                }


            }
            }
        }
        else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
        //登录成功就跳回首页
       return "redirect:http://gulimall.com";
    }
}
